package com.henu.zmb;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.henu.R;
import com.henu.yizhiya.util.PerUtil;
import com.henu.zmb.DBhelper.DBhelper;
import com.henu.zmb.entity.LoseGoods;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UploadFileListener;

public class AddLoseGoods_Activity extends AppCompatActivity {
    ImageView image ;
    EditText name;
    EditText time;
    EditText site;
    EditText message;
    Button submit;
    ImageButton aalg_return;
    BmobFile bmob_File = null;
    Uri fileUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_losegood);
        image = (ImageView)findViewById(R.id.aalg_ivimage);
        name = (EditText)findViewById(R.id.aalg_tvtitle);
        site = (EditText)findViewById(R.id.aalg_tvsite);
        time = (EditText)findViewById(R.id.aalg_tvtime);
        message = (EditText)findViewById(R.id.aalg_tvmessage);
        submit = (Button)findViewById(R.id.aalg_bsubmit);
        aalg_return = (ImageButton)findViewById(R.id.aalg_return);
        image.setImageResource(R.mipmap.addimage);
        Bmob.initialize(this, "a24db0fac16b375a97072b85080ea20f");
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new PerUtil().checkPerm(AddLoseGoods_Activity.this);
                //创建对话框
                AlertDialog.Builder dialog = new AlertDialog.Builder(AddLoseGoods_Activity.this);
                dialog.setTitle("上传图片");
                dialog.setPositiveButton("从图库中选取", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("image/*");
                        startActivityForResult(intent,1);
                    }
                }).setNegativeButton("从照相机中获取", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        fileUri = getOutputMediaFileUri(0); //得到存储地址的Uri
                        //image.setImageIcon((Icon.createWithBitmap(fileUri));
                        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //此action表示进行拍照
                        i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  //指定图片的输出地址
                        startActivityForResult(i, 0);
                    }
                });
                dialog.create();
                dialog.show();
            }
        });
        // 提交
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoseGoods lg = new LoseGoods();
                lg.setUserId(BmobUser.getCurrentUser());
                lg.setLoseGoods_Image(bmob_File);
                lg.setLoseGoods_Message(message.getText().toString().trim());
                lg.setLoseGoods_Nmae(name.getText().toString().trim());
                lg.setLoseGoods_Site(site.getText().toString().trim());
                lg.setLoseGoods_Time(time.getText().toString().trim());
                DBhelper<LoseGoods> db =new DBhelper<LoseGoods>();
                db.Add(lg);
                Intent intent = new Intent(AddLoseGoods_Activity.this,UserLoseGoods_MainActivity.class); // 设置跳转的路径
                startActivity(intent); // 跳转
                finish();
            }
        });
        aalg_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
    private File createImgFile(){
        //确定文件名
        String fileName="img_"+new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())+".jpg";
//        File dir=getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//        File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//        File dir=Environment.getExternalStorageDirectory();
        File dir;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            dir = Environment.getExternalStorageDirectory();
        }else{
            dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir,fileName);
        try{
            if(tempFile.exists()){
                tempFile.delete();
            }
            tempFile.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        //获取文件路径
        String photoPath = tempFile.getAbsolutePath();
        return tempFile;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1){
            // 获取选择的图片
           Uri photoUri=data.getData();
           //获取照片路径
            String[] filePathColumn={MediaStore.Images.Media.DATA};
            Cursor cursor=getContentResolver().query(photoUri,filePathColumn,null,null,null);
            cursor.moveToFirst();
            String path = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
            System.out.println(path);
            final BmobFile bmobFile  = new BmobFile(new File(path));
            // 在本地显示图片
            Bitmap map = BitmapFactory.decodeFile(path);
            image.setImageBitmap(map);

            bmobFile.uploadblock(new UploadFileListener(){
                    @Override
                    public void done(BmobException e) {
                    System.out.print("+++++++++++++++++++++++++++++++++++++++++图片上传成功1！");
                        // 全局变量
                    bmob_File = bmobFile;
                }
            });
        }
        if(requestCode==0){
            File file = createImgFile();
            final BmobFile bmobFile  = new BmobFile(file);
            Bitmap map= BitmapFactory.decodeFile(file.getPath());
            image.setImageBitmap(map);
            bmobFile.uploadblock(new UploadFileListener(){
                @Override
                public void done(BmobException e) {
                    System.out.print("+++++++++++++++++++++++++++++++++++++++++图片上传成功0！");
                    bmob_File = bmobFile;

                }
            });
        }

    }
    /** 为保存图片或视频创建一个文件地址 */
    private static Uri getOutputMediaFileUri(int type){

        return Uri.fromFile(getOutputMediaFile(type));
    }
    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){

        // 首先检测外部SDCard是否存在并且可读可写
        if (!Environment.getExternalStorageState().equals("mounted")) {
            return null;
        }
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory().getPath());


        // 如果存储路径不存在，则创建
        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()) {
            if (! mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == 0) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".jpg");
        } else {
            return null;
        }

        return mediaFile;
    }

}
